<template>
  <basic-layout title="我的相册" class="album-page">
    <me-upload
      v-model="fileList"
      :max-count="9"
      :max-size="5 * 1024 * 1024"
      multiple
      @upload-success="handleUploadSuccess"
      @upload-error="handleUploadError"
    >
      <div class="upload-area">
        <van-icon name="photograph" size="32" />
        <span>上传照片</span>
      </div>
    </me-upload>

    <!-- 相册网格 -->
    <div class="album-grid">
      <div
        v-for="(item, index) in fileList"
        :key="index"
        class="grid-item"
        @click="() => handlePreview(item)"
      >
        <van-image
          :src="item.url || item.content"
          fit="cover"
        />
      </div>
    </div>
  </basic-layout>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { showToast } from 'vant'
import type { UploaderFileListItem } from 'vant'
import MeUpload from '@/components/MeUpload/index.vue'

const fileList = ref<UploaderFileListItem[]>([])

const handleUploadSuccess = (file: UploaderFileListItem) => {
  showToast('上传成功')
}

const handleUploadError = (error: Error) => {
  showToast('上传失败：' + error.message)
}

const handlePreview = (file: UploaderFileListItem) => {
  // 调用上传组件的预览方法
  const uploadComponent = getCurrentInstance()?.refs.upload as InstanceType<typeof MeUpload>
  uploadComponent?.preview(file)
}
</script>

<style lang="less" scoped>
.album-page {
  padding: 16px;

  .upload-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 120px;
    background: #f7f8fa;
    border-radius: 8px;
    margin-bottom: 16px;

    span {
      margin-top: 8px;
      color: #666;
      font-size: 14px;
    }
  }

  .album-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;

    .grid-item {
      aspect-ratio: 1;
      border-radius: 8px;
      overflow: hidden;

      .van-image {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
